from flask import request


class requestPacket:
    def __init__(self, ask: request):
        self._this: request = ask
        self._transmit = True
        self._code = 200
        if self._this.method == "POST":
            self._data = self._this.data
        else:
            self._data = self._this.args

    def getType(self):
        """
        获取请求方式 GET/POST
        :return:
        """
        return self._this.method

    def setTransmit(self, v: bool):
        """
        设置事件是否向下传递(仅中间层设置此参数有效)
        :param v:
        :return:
        """
        self._transmit = v

    def isTransmit(self) -> bool:
        """
        获取事件是否向下传递
        :return:
        """
        return self._transmit

    def setData(self, v: str | dict):
        """
        设置请求的 结构体/参数
        :param v: 新的数据
        :return:
        """
        self._data = v

    def getData(self) -> str | dict:
        """
        获取请求的 结构体/url参数\n
        注:
            POST请求中会丢弃url参数只考虑body\n
            GET请求中会丢弃body参数只考虑url参数\n
        :return:
        """
        return self._data

    def getBytes(self) -> bytes:
        """
        获取请求的原始字节
        :return:
        """
        return self._this.get_data()

    def getCode(self) -> int:
        """
        获取请求的响应码
        :return:
        """
        return self._code

    def setCode(self, code: int):
        """
        设置请求的响应码
        :param code: 响应码
        :return:
        """
        self._code = code

    def getIP(self) -> str:
        """
        获取客户端IP
        :return:
        """
        return self._this.remote_addr

    def getHeaders(self, key: str) -> str | None:
        """
        获取请求头信息\n
        安全警告: 不要试图通过 X-Real-Ip 获取 代理/源IP 这不属于任何标准且易于伪造
        :param key: 请求头键名
        :return:
        """
        if key in self._this.headers.keys():
            return self._this.headers.get(key)
        else:
            return None

    def setHeaders(self, key: str, val: str):
        """
        设置请求头信息\n
        :param val: 值
        :param key: 请求头键名
        :return:
        """
        self._this.headers[key] = val

    def isFile(self) -> bool:
        """
        判断上传的是否是文件
        :return:
        """
        return self.getHeaders("enctype") == "multipart/form-data"
